package top.riske.gen3d.common.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 允许所有跨域
 * created by vital on 2024/11/11 下午4:23
 */
@Slf4j
public class CorsPreFlightFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("CorsPreFlightFilter init");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        log.info("CorsPreFlightFilter start, request URI: {}", httpRequest.getRequestURI());

        // 动态设置允许的 Origin
        String origin = httpRequest.getHeader("Origin");
        if (origin != null) {
            httpResponse.setHeader("Access-Control-Allow-Origin", origin);
        }else{
            httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        }
        // 处理 OPTIONS 请求，设置响应头允许跨域
        if("OPTIONS".equals(httpRequest.getMethod())){
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            // 添加必要的 CORS 头
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            httpResponse.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
            httpResponse.setHeader("Access-Control-Expose-Headers", "Authorization");
            httpResponse.setHeader("Access-Control-Max-Age", "3600");
            return;
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        log.info("CorsPreFlightFilter destroy");
    }

    private String getBaseRequestURL(HttpServletRequest request) {
        StringBuilder url = new StringBuilder();
        url.append(request.getScheme()).append("://").append(request.getServerName());
        if (request.getServerPort() != 80 && request.getServerPort() != 443) {
            url.append(':').append(request.getServerPort());
        }
        return url.toString();
    }


    private String getFullRequestURL(HttpServletRequest request) {
        StringBuilder url = new StringBuilder();
        url.append(request.getScheme()).append("://").append(request.getServerName());
        if (request.getServerPort() != 80 && request.getServerPort() != 443) {
            url.append(':').append(request.getServerPort());
        }
        url.append(request.getRequestURI());
        return url.toString();
    }

}
